from calendar import c
from tkinter import font
from matplotlib.font_manager import FontProperties
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

# 记录种类及数量


def count(column):
    column_type = {}
    for obj in column:
        if obj in column_type.keys() and pd.notnull(obj):
            column_type[obj] = column_type[obj] + 1
        else:
            column_type[obj] = 0
    temp = column_type.copy()
    column_type.clear()
    # 字典
    column_type = {k: v for k, v in sorted(
        temp.items(), key=lambda item: item[1], reverse=True)}
    return column_type


'''
折线图
data:pandasFrame数据
university:选定的大学
column:选定的随年份变化的属性
dir:输出文件夹
'''


def draw_line(data, university, column, dir):
    x = np.array([2017, 2018, 2019, 2020, 2021, 2022])
    data1 = data.loc[data['university'] == university]
    data1 = data1.drop(
        columns=['research_output', 'country', 'city', 'region', 'type', 'size'])
    if column == 'rank_display':
        y = np.array(data1['rank_display'].apply(lambda x: int(x)))
    else:
        y = np.array(data1[column])
    plt.figure(facecolor='white')
    plt.plot(x, y, marker='o', linestyle='dashed', c='red')
    plt.grid(color='r', linestyle='--', linewidth=0.5)
    plt.title(university+'    ' + column + ' - year')
    plt.xlabel("year")
    plt.ylabel(column)
    plt.savefig(r'./' + dir + r'/' + university+'_' +
                column.replace('/', 'Or') + '.png', bbox_inches='tight', dpi=1000)
    # plt.show()


'''
柱状图
data:pandasFrame数据
column:选定的的属性
dir:输出文件夹
year:哪一年的数据
'''


def draw_bar(data, column, dir, year):
    column_type = count(data[column])
    labels = list(column_type.keys())
    sizes = list(column_type.values())
    plt.figure(figsize=(12, 9), dpi=80, facecolor='white')
    # 防止种类过多只取前8个
    if len(column_type) > 8:
        labels = labels[:8]
        sizes = sizes[:8]
    plt.title('numbers of ' + column + ' in ' + year, fontsize=16)
    for a, b in zip(labels, sizes):
        plt.text(a, b + 0.05, '%.0f' %
                 b, ha='center', va='bottom', fontsize=8)
    plt.bar(labels, sizes, color="#4CAF50", width=0.5)
    plt.savefig(r'./' + dir + r'/' +
                column.replace('/', 'Or') + year + '.png')


'''
饼状图
data:pandasFrame数据
column_name:选定的的属性
dir:输出文件夹
year:哪一年的数据
'''


def draw_pie(data, column_name, dir, year):
    column_type = count(data[column_name])
    if len(column_type) > 7:
        temp = column_type.copy()
        column_type.clear()
        i = sum = 0
        for key in temp.keys():
            if i < 20:
                column_type[key] = temp[key]
            else:
                sum += temp[key]
            i += 1
        column_type['others'] = sum
    labels = list(column_type.keys())
    sizes = list(column_type.values())
    # 36,27
    plt.figure(figsize=(12, 9), dpi=80, facecolor='white')
    plt.pie(sizes,
            labels=labels,
            autopct='%3.2f%%',
            shadow=False,
            startangle=180,
            radius=1.2,
            pctdistance=0.75,
            )
    plt.legend(loc='upper left')
    plt.savefig(r'./' + dir + r'/' +
                column_name.replace('/', 'Or') + year+'.png')


# 世界地图
# def draw_map(data, dir):
#     plt.figure(figsize=(40, 30))
#     m = Basemap()
#     m.drawcoastlines()
#     m.drawcountries(color='grey', linewidth=2)
#     m.drawstates()
#     m.drawmapboundary(fill_color='#87CEEB')
#     m.fillcontinents(color='green', lake_color='#87CEEB')
#     # 经纬线
#     m.drawparallels(circles=np.linspace(-90, 90, 7),
#                     labels=[1, 0, 0, 0], color='gray')
#     m.drawmeridians(meridians=np.linspace(-180, 180, 13),
#                     labels=[0, 0, 0, 1], color='pink')
#     # 两数据集经纬叫法不一致
#     if dir == 'starbuck':
#         lon = data['Longitude']
#         lat = data['Latitude']
#     else:
#         lon = data['lng']
#         lat = data['lat']
#     # 打点
#     m.scatter(lon, lat, s=2, c='red')
#     plt.savefig(r'./' + dir + r'/' + 'Worldmap' + '.png')
